package com.huitongjy.common.generator;

/**
 * 自定义的ID生成器
 * <p>
 *      Use snowflake algorithm. Length is 64 bit.
 * </p>
 *
 * <pre>
 * 1bit   符号位 不使用
 * 0bit   高位补位(当机器位+自增序列为小于22时,可以自定义补位)
 * 41bits 时间戳
 * 10bit 机器Id
 * 12bit 自增序列
 * </pre>
 *
 * @author guan
 */
public class ExtraKeyGenerator extends SimpleKeyGenerator {

    /**
     * 时间位 41 (毫秒)
     */
    private static final int EPOCH_BITS = 41;

    /**
     * 高位补位偏移量
     */
    private final int extraLeftShiftBits;

    /**
     * 高位补位
     */
    private final long extraValue;

    public ExtraKeyGenerator(int workerIdBits, int sequenceBits, long workerId, long extraValue) {
        super(workerIdBits, sequenceBits, workerId);
        this.extraLeftShiftBits = EPOCH_BITS + workerIdBits + sequenceBits;
        if (extraValue >= (1<<(63 - extraLeftShiftBits))) {
            throw new RuntimeException("生成器位数溢出");
        }
        this.extraValue = extraValue;
    }

    @Override
    protected long buildGenerateKey(long currentMillis, long sequence) {
        return extraValue << extraLeftShiftBits | super.buildGenerateKey(currentMillis, sequence);
    }
}
